import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import { Row, Col, Steps, Typography, Form, Input, Radio, Select, DatePicker, Button, RadioChangeEvent, message } from 'antd';
import styles from './style.less';
import DebounceSelect from './components/DebounceSecect';
import { BusinessItem } from './data';
import { selectSearch, getBusiness, save, update, getDetail } from './service';
import Rules from './mockData';
import moment from 'moment';
console.log(Rules)

const { Step } = Steps;
const { Title } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;
// DatePicker, Switch


export default function Detail(props: any) {
  const [basicForm] = Form.useForm();
  const [budgetBidForm] = Form.useForm();
  // const params = useLocation();
  console.log(props, '详情的props');
  // const name = history.location.state.name;
  const [targetValue, setTargetValue] = useState(1);
  const [areaValue, setAreaValue] = useState(1);
  const [interValue, setInterValue] = useState('不限');
  const [BusinessOptions, setBusinessOptions] = useState<any>([]);
  const [house, setHouse] = useState<any>([]);
  const [basic, setBasic] = useState(false);
  const [budget, setBudget] = useState(false);

  const query = props.location.query;

  useEffect(() => {
    const params = {};
    getBusiness(params).then(res => {
      console.log(res, '推广业务下拉结果');
      if (res) {
        setBusinessOptions(res);
      }
    })
    if (query.type === '2') {
      getPlanDetail();
    }
    // return () => {
    //   setBusinessOptions([]);
    // }
  }, [])

  // const onFormFinish = (formName: any, info: { values: any, forms: any }) => {
  //   console.log('Success:', formName, info);
  // };

  const targetChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setTargetValue(e.target.value);
  };

  const areaChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setAreaValue(e.target.value);
  };

  const interChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setInterValue(e.target.value);
  };

  // 新增
  const saveClick = (type: number) => {
    // console.log(type, basicForm.getFieldsValue(), budgetBidForm.getFieldsValue());
    // 新增
    // const basicFormValues = basicForm.getFieldsValue();
    // const budgetBidFormValues = budgetBidForm.getFieldsValue();
    let tempObj = {};
    basicForm.validateFields().then(values => {
      console.log(values);
      setBasic(true);
      tempObj = { ...values };
    }).catch(errorInfo => {
      console.log(errorInfo, 'tempObj');
      setBasic(false);
    })

    budgetBidForm.validateFields().then(values => {
      console.log(values);
      setBudget(true);
      tempObj = { ...values };
    }).catch(errorInfo => {
      console.log(errorInfo);
      setBudget(false);
    })

    if (basic && budget) {
      saveData(tempObj, type);
    } else {
      message.error('请完成表单在进行提交！')
    }
  };

  const saveData = (tempObj: any, type: number) => {
    const params = {
      ...tempObj,
      housesId: tempObj.housesId.value * 1,
      housesName: tempObj.housesId.label,
      startDate: moment(tempObj.extensionTime[0]).format('YYYY-MM-DD'),
      endDate: moment(tempObj.extensionTime[1]).format('YYYY-MM-DD'),
      timeStep: [0, 23],
      coefficientMb: tempObj.coefficientMb ? tempObj.coefficientMb * 1 : '',
      coefficientPc: tempObj.coefficientPc ? tempObj.coefficientPc * 1 : ''
    };
    save(params).then(res => {
      console.log(res, '新增数据结果');
      if (res) {
        if (type === 1) {
          // 新增跳转单元表单
          history.push('/promotion/promotion_unit/detail', {
            planId: res,
          });
        } else {
          // 回跳计划列表
          history.goBack();
        }
      }
    })
  }

  // 编辑
  const updateClick = (type: number) => {
    let tempObj = {};
    basicForm.validateFields().then(values => {
      console.log(values);
      setBasic(true);
      tempObj = { ...values };
    }).catch(errorInfo => {
      console.log(errorInfo, 'tempObj');
      setBasic(false);
    })

    budgetBidForm.validateFields().then(values => {
      console.log(values);
      setBudget(true);
      tempObj = { ...values };
    }).catch(errorInfo => {
      console.log(errorInfo);
      setBudget(false);
    })

    if (basic && budget) {
      updateData(tempObj, type);
    } else {
      message.error('请完成表单在进行提交！')
    }
  };

  const updateData = (tempObj: any, type: number) => {
    const params = {
      ...tempObj,
      housesId: tempObj.housesId.value * 1,
      housesName: tempObj.housesId.label,
      startDate: moment(tempObj.extensionTime[0]).format('YYYY-MM-DD'),
      endDate: moment(tempObj.extensionTime[1]).format('YYYY-MM-DD'),
      timeStep: [0, 23],
      coefficientMb: tempObj.coefficientMb ? tempObj.coefficientMb * 1 : '',
      coefficientPc: tempObj.coefficientPc ? tempObj.coefficientPc * 1 : '',
      planId: query.id * 1
    };
    update(params).then(res => {
      console.log(res, '编辑数据结果');
      if (res) {
        if (type === 1) {
          // 新增跳转单元表单
          history.push('/promotion/promotion_unit/index', {
            planId: query.id,
          });
        } else {
          // 回跳计划列表
          history.goBack();
        }
      }
    })
  }

  // 取消按钮
  const handleCancel = () => {
    basicForm.resetFields();
    budgetBidForm.resetFields();
    history.goBack();
  }

  // 获取计划详情
  const getPlanDetail = () => {
    const params = {
      planId: query.id * 1
    }
    getDetail(params).then(res => {
      console.log(res, '获取计划详情');
      selectSearch(res.housesName.split("(")[0]).then(result => {
        console.log(result, '初始获取楼盘集合');
        const newResult = result.map((item: any) => ({
          label: `${item.buildingAlias}(${item.cityname}-${item.id})`,
          value: item.id,
          key: item.id
        }))
        setHouse(newResult);
      })
      res.target = res.target === '2' ? 2 : 1;
      res.extensionTime = [moment(res.startDate), moment(res.endDate)];
      res.coefficientType = res.coefficientType === '1' ? 1 : 2;
      res.business = res.business * 1;
      basicForm.setFieldsValue(res);
      budgetBidForm.setFieldsValue(res);
    })
  }

  return (
    <Row className={styles.row}>
      <Col flex={1}>
        <Steps progressDot current={0} direction="vertical" className={styles.step}>
          <Step
            title="推广计划"
            description={
              <>
                <div>基础设置</div>
                <div>预算及出价</div>
              </>
            }
          />
          <Step
            title="推广单元"
            description={
              <>
                <div>单元设置</div>
                <div>关键词设置</div>
              </>
            }
          />
          <Step
            title="推广创意"
            description={
              <>
                <div>创意文案</div>
                <div>落地页信息</div>
              </>
            }
          />
        </Steps>
      </Col>
      <Col flex={22}>
        <div className={styles.container}>
          {/* <Form.Provider onFormFinish={onFormFinish}> */}
            {/* 标题 */}
            <Title level={5}>基础设置</Title>
            {/* 基础设置表单 */}
            <Form form={basicForm} name="basicForm" className={styles.form} labelCol={{ span: 6 }} initialValues={{ target: 1, area: '全部地域', extensionInterval: '不限' }}>
              <Form.Item name='planName' label='计划名称' rules={Rules.basicForm.planName} className={styles.formItem}>
                <Input placeholder='请输入计划名称' allowClear className={styles.formItemContent} />
              </Form.Item>
              <Form.Item name='housesId' label='关联楼盘' rules={Rules.basicForm.build} className={styles.formItem}>
                <DebounceSelect
                  placeholder="关联楼盘"
                  allowClear
                  className={styles.formItemContent}
                  newOpt={house}
                  fetchOptions={selectSearch}
                />
              </Form.Item>
              <Form.Item name='target' label='推广目标' rules={Rules.basicForm.target} className={styles.formItem}>
                <Radio.Group onChange={targetChange} value={targetValue} className={styles.formItemContent}>
                  <Radio value={1}>网站链接</Radio>
                  <Radio value={2}>应用推广</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item name='business' label='推广业务' className={styles.formItem}>
                <Select allowClear placeholder="推广业务" className={styles.formItemContent}>
                  {/* <Option value="房产平台">房产平台  房产家居-房产中介-房产平台</Option>
                  <Option value="新房买卖">新房买卖  房产家居-房产中介-房屋出售-新房买卖</Option> */}
                  {BusinessOptions.map((item: BusinessItem) => (<Option key={item.business} value={item.business*1}>{item.businessName}</Option>))}
                </Select>
              </Form.Item>
              <Form.Item name='area' label='推广地域' rules={Rules.basicForm.area} className={styles.formItem}>
                <Radio.Group onChange={areaChange} value={areaValue} className={styles.formItemContent}>
                  <Radio value={'全部地域'}>账户地域</Radio>
                  <Radio value={'自定义计划地域'}>自定义计划地域</Radio>
                </Radio.Group>
                {/* 根据单选项切换相应内容 */}
              </Form.Item>
              <Form.Item name='extensionTime' label='推广时间' rules={Rules.basicForm.extensionTime} className={styles.formItem}>
                <RangePicker className={styles.formItemContent} />
              </Form.Item>
              <Form.Item name='extensionInterval' label='推广时段' rules={Rules.basicForm.extensionInterval} className={styles.formItem}>
                <Radio.Group onChange={interChange} value={interValue} className={styles.formItemContent}>
                  <Radio value={'不限'}>不限</Radio>
                  <Radio value={'自定义'}>自定义</Radio>
                </Radio.Group>
              </Form.Item>
            </Form>
            {/* 标题 */}
            <Title level={5}>预算及出价</Title>
            {/* 预算及出价表单 */}
            <Form form={budgetBidForm} name="budgetBidForm" className={styles.form} labelCol={{ span: 6 }} initialValues={{ coefficientType: 2 }}>
              <Form.Item label='每日预算' name='budget' rules={Rules.budgetBidForm.budget} className={styles.formItem}>
                <Form.Item name='budget'>
                  <Input placeholder='请输入每日预算' allowClear className={styles.formItemContent} />
                </Form.Item>
                <span className={styles.tips}>每日预算值不可为小数，并且数值不低于50</span>
              </Form.Item>
            <Form.Item name='coefficientType' label='设备出价设置' rules={Rules.budgetBidForm.coefficientType} className={styles.formItem}>
                <Radio.Group className={styles.formItemContent}>
                  <Radio value={1}>计算机出价比例</Radio>
                  <Radio value={2}>移动出价比例</Radio>
                </Radio.Group>
                {/* 根据单选项切换相应内容 */}
              </Form.Item>
              {budgetBidForm.getFieldValue('coefficientType') === 2 ?
                <Form.Item label='移动出价' name='coefficientMb' rules={Rules.budgetBidForm.coefficientMb} className={styles.formItem}>
                  <Form.Item name='coefficientMb'>
                    <Input placeholder='请输入移动出价' allowClear className={styles.formItemContent} />
                  </Form.Item>  * 计算机出价
                </Form.Item>
                : <Form.Item label='计算机出价' name='coefficientPc' rules={Rules.budgetBidForm.coefficientPc} className={styles.formItem}>
                  <Form.Item name='coefficientPc'>
                    <Input placeholder='请输入计算机出价' allowClear className={styles.formItemContent} />
                  </Form.Item>  * 移动出价
                </Form.Item>
              }
            </Form>
          {/* </Form.Provider> */}
          <div>
            {query.type === '1' ? <>
              <Button type='primary' className={styles.saveBtn} onClick={() => { saveClick(1) }}>保存并新建单元</Button>
              <Button type='primary' className={styles.saveBtn} onClick={() => { saveClick(2) }}>仅保存</Button>
            </> : <>
              <Button type='primary' className={styles.saveBtn} onClick={() => { updateClick(1) }}>跳转单元管理</Button>
              <Button type='primary' className={styles.saveBtn} onClick={() => { updateClick(2) }}>仅保存</Button>
            </>}
            <Button onClick={handleCancel}>取消</Button>
          </div>
        </div>
      </Col>
    </Row>
  );
}
